import Phaser from "phaser";

interface customParamType {
  zoomRatio: number;
  gameWidth: number;
  gameHeight: number;
}

/**
 * 找茬游戏场景类
 * 实现了一个找茬游戏的核心逻辑，包括：
 * 1. 两张相似图片的展示
 * 2. 不同点的标记和检测
 * 3. 分数系统：找出不同点获得分数
 * 4. 动画系统：包含点击、提示等动画效果
 */
export class FindScene extends Phaser.Scene {
  private score: number = 0; // 玩家得分
  private scoreText: Phaser.GameObjects.Text | null = null; // 分数显示
  private remainingDiffs: number = 0; // 剩余需要找出的不同点数量
  private remainingText: Phaser.GameObjects.Text | null = null; // 剩余数量显示
  private gameWidth: number; // 游戏宽度
  private gameHeight: number; // 游戏高度
  private zoomRatio: number; // 缩放比例
  private originalImage: Phaser.GameObjects.Image | null = null; // 原始图片
  private modifiedImage: Phaser.GameObjects.Image | null = null; // 修改后的图片
  private diffPoints: { x: number, y: number, found: boolean }[] = []; // 不同点位置数组
  private circles: Phaser.GameObjects.Graphics[] = []; // 圈出不同点的圆圈
  private hintButton: Phaser.GameObjects.Text | null = null; // 提示按钮
  private hintCount: number = 3; // 提示次数

  constructor(config: Phaser.Types.Scenes.SettingsConfig, customParam: customParamType) {
    super(config);
    this.gameWidth = customParam.gameWidth;
    this.gameHeight = customParam.gameHeight;
    this.zoomRatio = customParam.zoomRatio;
  }

  preload(): void {
    // 加载游戏资源
    this.load.image("original", "/image/original.png"); // 原始图片
    this.load.image("modified", "/image/modified.png"); // 修改后的图片
  }

  create(): void {
    // 创建分数显示
    this.createScoreDisplay();

    // 创建剩余不同点显示
    this.createRemainingDisplay();

    // 创建游戏说明
    this.createGameInstructions();

    // 设置不同点位置（这里需要根据实际图片设置）
    this.diffPoints = [
      { x: 100, y: 100, found: false },
      { x: 200, y: 150, found: false },
      { x: 300, y: 200, found: false },
      { x: 150, y: 250, found: false },
      { x: 250, y: 300, found: false }
    ];
    this.remainingDiffs = this.diffPoints.length;

    // 更新剩余数量显示
    this.updateRemainingText();

    // 创建图片
    this.createImages();

    // 创建提示按钮
    this.createHintButton();

    // 添加点击事件
    this.setupClickHandlers();
  }

  private createGameInstructions(): void {
    const instructions = [
      '游戏说明：',
      '1. 找出两张图片中的不同之处',
      '2. 点击任意一张图中的不同点',
      '3. 找出所有不同获得胜利',
      `4. 共有 ${this.diffPoints.length} 处不同`,
      '5. 每次错误点击将扣除50分',
      '6. 可使用3次提示机会'
    ];

    const instructionsText = this.add.text(16, 100, instructions, {
      fontSize: '16px',
      color: '#ffffff',
      align: 'left'
    });
    instructionsText.setDepth(1000);
  }

  private createHintButton(): void {
    this.hintButton = this.add.text(this.gameWidth - 150, 16, `提示(${this.hintCount})`, {
      fontSize: '24px',
      color: '#ffffff',
      backgroundColor: '#000000',
      padding: { x: 10, y: 5 }
    });
    this.hintButton.setInteractive();
    this.hintButton.on('pointerdown', () => this.showHint());
  }

  private showHint(): void {
    if (this.hintCount <= 0) return;

    // 找到一个未发现的不同点
    const unFoundDiff = this.diffPoints.find(point => !point.found);
    if (unFoundDiff) {
      // 显示闪烁提示
      const hintCircle = this.add.graphics(); //绘制基本形状（矩形，圆和多边形）
      hintCircle.lineStyle(3, 0xffff00, 1);

      // 在两张图片上都显示提示
      if (this.originalImage && this.modifiedImage) {
        const originalX = this.originalImage.x - this.originalImage.displayWidth / 2 + unFoundDiff.x;
        const originalY = this.originalImage.y - this.originalImage.displayHeight / 2 + unFoundDiff.y;
        const modifiedX = this.modifiedImage.x - this.modifiedImage.displayWidth / 2 + unFoundDiff.x;
        const modifiedY = this.modifiedImage.y - this.modifiedImage.displayHeight / 2 + unFoundDiff.y;

        // 创建闪烁动画
        this.tweens.add({
          targets: hintCircle,
          alpha: { from: 1, to: 0 },
          duration: 500,
          repeat: 3,
          onUpdate: () => {
            hintCircle.clear();
            hintCircle.lineStyle(3, 0xffff00, hintCircle.alpha);
            hintCircle.strokeCircle(originalX, originalY, 25);
            hintCircle.strokeCircle(modifiedX, modifiedY, 25);
          },
          onComplete: () => {
            hintCircle.destroy();
          }
        });

        this.hintCount--;
        if (this.hintButton) {
          this.hintButton.setText(`提示(${this.hintCount})`);
        }
      }
    }
  }

  private createScoreDisplay(): void {
    this.scoreText = this.add.text(16, 16, 'Score: 0', {
      fontSize: '32px',
      color: '#ffffff',
      fontStyle: 'bold'
    });
    this.scoreText.setDepth(1000);
  }

  private createRemainingDisplay(): void {
    this.remainingText = this.add.text(16, 60, `Remaining: ${this.remainingDiffs}`, {
      fontSize: '32px',
      color: '#ffffff',
      fontStyle: 'bold'
    });
    this.remainingText.setDepth(1000);
  }

  private createImages(): void {
    const spacing = 20; // 图片之间的间距
    const imageWidth = (this.gameWidth - spacing * 3) / 2; // 计算图片宽度
    const scale = imageWidth / 800; // 假设原始图片宽度为800px

    // 创建左侧原始图片
    this.originalImage = this.add.image(
      spacing + imageWidth / 2,
      this.gameHeight / 2,
      'original'
    );
    this.originalImage.setScale(scale);
    this.originalImage.setInteractive();// 使图像对象可以响应鼠标或触摸事件。

    // 创建右侧修改后的图片
    this.modifiedImage = this.add.image(
      this.gameWidth - spacing - imageWidth / 2,
      this.gameHeight / 2,
      'modified'
    );
    this.modifiedImage.setScale(scale);
    this.modifiedImage.setInteractive();
  }

  private setupClickHandlers(): void {
    // 为两张图片添加点击事件
    if (this.originalImage && this.modifiedImage) {
      this.originalImage.on('pointerdown', (pointer: Phaser.Input.Pointer) => {
        this.handleImageClick(pointer, true);
      });

      this.modifiedImage.on('pointerdown', (pointer: Phaser.Input.Pointer) => {
        this.handleImageClick(pointer, false);
      });
    }
  }

  private handleImageClick(pointer: Phaser.Input.Pointer, isOriginal: boolean): void {
    // 获取点击位置相对于图片的坐标
    const image = isOriginal ? this.originalImage : this.modifiedImage;
    if (!image) return;

    const localX = pointer.x - (image.x - image.displayWidth / 2);
    const localY = pointer.y - (image.y - image.displayHeight / 2);

    // 检查是否点击到不同点
    const clickedDiff = this.diffPoints.find(point => {
      const distance = Phaser.Math.Distance.Between(point.x, point.y, localX, localY);
      return !point.found && distance < 30; // 30px的判定范围
    });

    if (clickedDiff) {
      this.handleCorrectClick(clickedDiff, isOriginal);
    } else {
      this.handleWrongClick(pointer.x, pointer.y);
    }
  }

  private handleCorrectClick(diffPoint: { x: number, y: number, found: boolean }, isOriginal: boolean): void {
    diffPoint.found = true;
    this.remainingDiffs--;
    this.updateScore(100);
    this.updateRemainingText();

    // 在两张图片上都画圈
    this.drawCircle(diffPoint.x, diffPoint.y, isOriginal);
    this.drawCircle(diffPoint.x, diffPoint.y, !isOriginal);

    // 播放正确音效或动画
    this.showCorrectEffect(diffPoint.x, diffPoint.y, isOriginal);

    // 检查游戏是否完成
    if (this.remainingDiffs === 0) {
      this.gameComplete();
    }
  }

  private showCorrectEffect(x: number, y: number, isOriginal: boolean): void {
    const image = isOriginal ? this.originalImage : this.modifiedImage;
    if (!image) return;

    const effectX = image.x - image.displayWidth / 2 + x;
    const effectY = image.y - image.displayHeight / 2 + y;

    // 创建一个星形粒子效果
    const particles = this.add.particles('particle');
    const emitter = particles.createEmitter({
      x: effectX,
      y: effectY,
      speed: { min: -100, max: 100 },
      angle: { min: 0, max: 360 },
      scale: { start: 0.5, end: 0 },
      blendMode: 'ADD',
      lifespan: 1000,
      quantity: 20
    });

    // 1秒后停止粒子效果
    this.time.delayedCall(1000, () => {
      emitter.stop();
      particles.destroy();
    });
  }

  private handleWrongClick(x: number, y: number): void {
    // 显示错误提示动画
    const wrongMark = this.add.text(x, y, '×', {
      fontSize: '48px',
      color: '#ff0000'
    });
    wrongMark.setOrigin(0.5);

    this.tweens.add({
      targets: wrongMark,
      alpha: 0,
      y: y - 30,
      duration: 1000,
      onComplete: () => {
        wrongMark.destroy();
      }
    });

    // 扣分
    this.updateScore(-50);
  }

  private drawCircle(x: number, y: number, isOriginal: boolean): void {
    const image = isOriginal ? this.originalImage : this.modifiedImage;
    if (!image) return;

    const circle = this.add.graphics();
    circle.lineStyle(3, 0x00ff00, 1);
    circle.strokeCircle(
      image.x - image.displayWidth / 2 + x,
      image.y - image.displayHeight / 2 + y,
      20
    );
    this.circles.push(circle);

    // 添加圆圈动画
    this.tweens.add({
      targets: circle,
      scaleX: 1.2,
      scaleY: 1.2,
      duration: 200,
      yoyo: true,
      repeat: 1
    });
  }

  private updateScore(points: number): void {
    this.score += points;
    if (this.scoreText) {
      this.scoreText.setText(`Score: ${this.score}`);

      // 添加分数变化动画
      this.tweens.add({
        targets: this.scoreText,
        scale: 1.2,
        duration: 100,
        yoyo: true
      });
    }
  }

  private updateRemainingText(): void {
    if (this.remainingText) {
      this.remainingText.setText(`Remaining: ${this.remainingDiffs}`);
    }
  }

  private gameComplete(): void {
    // 创建半透明背景
    const overlay = this.add.rectangle(0, 0, this.gameWidth, this.gameHeight, 0x000000, 0.7);
    overlay.setOrigin(0);
    overlay.setDepth(1001);

    // 创建完成文本
    const gameOverText = this.add.text(
      this.gameWidth / 2,
      this.gameHeight / 2,
      [
        'Congratulations!',
        `Final Score: ${this.score}`,
        '\nPress SPACE to restart'
      ],
      {
        fontSize: '48px',
        color: '#ffffff',
        align: 'center',
        fontStyle: 'bold'
      }
    );
    gameOverText.setOrigin(0.5);
    gameOverText.setDepth(1002);

    // 添加重启游戏功能
    const keyboard = this.input.keyboard;
    if (keyboard) {
      keyboard.once('keydown-SPACE', () => {
        this.scene.restart();
      });
    }
  }

  update(): void {
    // 游戏循环更新逻辑
  }
} 